package com.kiki.song.service.impl;

import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson2.JSON;
import com.kiki.album.domain.Album;
import com.kiki.album.mapper.AlbumMapper;
import com.kiki.comment.mapper.CommentMapper;
import com.kiki.common.core.domain.entity.SysUser;
import com.kiki.favorite.mapper.FavoriteMapper;
import com.kiki.history.mapper.ListeningHistoryMapper;
import com.kiki.recommendations.domain.Recommendations;
import com.kiki.recommendations.mapper.RecommendationsMapper;
import com.kiki.searchlog.domain.SearchLogDTO;
import com.kiki.searchlog.domain.Searchlog;
import com.kiki.searchlog.mapper.SearchlogMapper;
import com.kiki.singer.domain.Singer;
import com.kiki.singer.mapper.SingerMapper;
import com.kiki.song.domain.main.*;
import com.kiki.song.domain.recommend.ActionType;
import com.kiki.song.domain.recommend.SongProfile;
import com.kiki.song.domain.recommend.UserActionEvent;
import com.kiki.song.domain.recommend.UserProfile;
import com.kiki.song.recommend.OffLineRecommendationEngine;
import com.kiki.song.recommend.OnLineRecommendationEngine;
import com.kiki.song_category.domain.SongCategory;
import com.kiki.song_category.mapper.SongCategoryMapper;
import com.kiki.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.kiki.song.mapper.SongMapper;
import com.kiki.song.service.ISongService;


/**
 * 音乐信息Service业务层处理
 * 
 * @author 林志毅
 * @date 2025-01-08
 */
@Service
public class SongServiceImpl implements ISongService 
{
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SongMapper songMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private SingerMapper singerMapper;

    @Autowired
    private ListeningHistoryMapper historyMapper;

    @Autowired
    private SearchlogMapper searchlogMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RecommendationsMapper recommendationsMapper;

    @Autowired
    private SongCategoryMapper songCategoryMapper;






    /**
     * 查询音乐信息
     * 
     * @param songId 音乐信息主键
     * @return 音乐信息
     */
    @Override
    public SongVo selectSongBySongId(Long songId)
    {
//        System.out.println("查询歌曲信息"+songMapper.selectSongBySongId(songId));
        SongVo songVo = new SongVo();
        Song song1 = songMapper.selectSongBySongId(songId);
        songVo.setSongId(song1.getSongId());
        songVo.setAlbumName(albumMapper.selectAlbumByAlbumId(song1.getAlbumId()).getAlbumName());
        songVo.setSongName(song1.getSongName());
        songVo.setSinger(song1.getSinger());
        songVo.setReleaseDate(song1.getReleaseDate());
        songVo.setImgUrl(song1.getImgUrl());
        songVo.setFileUrl(song1.getFileUrl());
        songVo.setLyric(song1.getLyric());
        songVo.setType(song1.getType());
        songVo.setCreateBy(song1.getCreateBy());
        songVo.setUpdateBy(song1.getUpdateBy());
        return songVo;
    }

    /**
     * 查询音乐信息列表
     * 
     * @param song 音乐信息
     * @return 音乐信息
     */
    @Override
    public List<SongVo> selectSongList(Song song)
    {
        List<Song>list =songMapper.selectSongList(song);
        System.out.println("所有歌曲的列表数据的长度：" + list.size());
        List<SongVo> listVo = new ArrayList<SongVo>();
        for (Song song1 : list) {
            SongVo songVo = new SongVo();
            songVo.setSongId(song1.getSongId());
            //通过歌曲id查询专辑名称
            Album album=albumMapper.selectAlbumByAlbumId(song1.getAlbumId());
            songVo.setAlbumName(album.getAlbumName());
            songVo.setSongName(song1.getSongName());
            songVo.setSinger(song1.getSinger());
            songVo.setReleaseDate(song1.getReleaseDate());
            songVo.setImgUrl(song1.getImgUrl());
            songVo.setFileUrl(song1.getFileUrl());
            songVo.setLyric(song1.getLyric());
            songVo.setType(song1.getType());
            listVo.add(songVo);
        }
        return listVo;
    }

    /**
     * 新增音乐信息
     * 
     * @param song 音乐信息
     * @return 结果
     */
    @Override
    public int insertSong(SongVo song)
    {
        //获取albumId
        Long albumId = albumMapper.selectAlbumIdByAlbumName(song.getAlbumName());

        //属性复制
        Song song1 =new Song();
        song1.setSongId(song.getSongId());
        song1.setAlbumId(albumId);
        song1.setSongName(song.getSongName());
        song1.setImgUrl(song.getImgUrl());
        song1.setFileUrl(song.getFileUrl());
        song1.setSinger(song.getSinger());
        song1.setReleaseDate(song.getReleaseDate());
        song1.setLyric(song.getLyric());
        song1.setType(song.getType());
        return songMapper.insertSong(song1);
    }

    /**
     * 修改音乐信息
     * 
     * @param song 音乐信息
     * @return 结果
     */
    @Override
    public int updateSong(SongVo song)
    {
        //获取albumId
        Long albumId =  albumMapper.selectAlbumIdByAlbumName(song.getAlbumName());
//        System.out.println("值为"+albumId);
        //属性复制
        Song song1 =new Song();
        song1.setSongId(song.getSongId());
        song1.setAlbumId(albumId);
        song1.setSongName(song.getSongName());
        song1.setImgUrl(song.getImgUrl());
        song1.setSinger(song.getSinger());
        song1.setFileUrl(song.getFileUrl());
        song1.setReleaseDate(song.getReleaseDate());
        song1.setLyric(song.getLyric());
        song1.setType(song.getType());
//        System.out.println("song1的值"+song1);
        return songMapper.updateSong(song1);
    }

    /**
     * 批量删除音乐信息
     * 
     * @param songIds 需要删除的音乐信息主键
     * @return 结果
     */
    @Override
    public int deleteSongBySongIds(Long[] songIds)
    {
        return songMapper.deleteSongBySongIds(songIds);
    }

    /**
     * 删除音乐信息信息
     * 
     * @param songId 音乐信息主键
     * @return 结果
     */
    @Override
    public int deleteSongBySongId(Long songId)
    {
        return songMapper.deleteSongBySongId(songId);
    }

    @Override
    public List<SongVo> selectSongListByAlbumId(Long albumId) {
        List<Song>list =songMapper.selectSongListByAlbumId(albumId);
//        System.out.println("list的值"+list);
        List<SongVo> listVo = new ArrayList<SongVo>();
        for (Song song1 : list) {
            SongVo songVo = new SongVo();
            songVo.setSongId(song1.getSongId());
            songVo.setSongName(song1.getSongName());
            songVo.setSinger(song1.getSinger());
            songVo.setReleaseDate(song1.getReleaseDate());
            songVo.setImgUrl(song1.getImgUrl());
            songVo.setFileUrl(song1.getFileUrl());
            songVo.setLyric(song1.getLyric());
            listVo.add(songVo);
        }
//        System.out.println("返回列表为："+listVo);
        return listVo;
    }

    @Override
    public List<SongVo> listFavoriteByUserId(Long userId) {
        List<Long> songIdList = favoriteMapper.listFavoriteByUserId(userId);
        List<SongVo> listVo = new ArrayList<SongVo>();
        for (Long songId : songIdList) {
            SongVo songVo = new SongVo();
            Song song = songMapper.selectSongBySongId(songId);
            songVo.setSongId(song.getSongId());
            songVo.setSongName(song.getSongName());
            songVo.setSinger(song.getSinger());
            songVo.setReleaseDate(song.getReleaseDate());
            songVo.setImgUrl(song.getImgUrl());
            songVo.setFileUrl(song.getFileUrl());
            songVo.setLyric(song.getLyric());
            listVo.add(songVo);
        }
        return listVo;
    }

    // 查询播放历史
    @Override
    public List<SongVo> listHistoryByUserId(Long userId) {
        List<Long> songIdList = historyMapper.listHistoryByUserId(userId);
        List<SongVo> listVo = new ArrayList<SongVo>();
        for (Long songId : songIdList) {
            SongVo songVo = new SongVo();
            Song song = songMapper.selectSongBySongId(songId);
            songVo.setSongId(song.getSongId());
            songVo.setSongName(song.getSongName());
            songVo.setSinger(song.getSinger());
            songVo.setReleaseDate(song.getReleaseDate());
            songVo.setImgUrl(song.getImgUrl());
            songVo.setFileUrl(song.getFileUrl());
            songVo.setLyric(song.getLyric());
            listVo.add(songVo);
        }
        return listVo;
    }

    /**
     * 获取热歌榜
     * @return
     */
    @Override
    public List<SongDTO> getHotSongList() {
        //先查询listening_history表中所有的歌曲的song_id(不重复)，插入到song_id列表中
        List<Long> songIdList =historyMapper.listSongIdList();
//        System.out.println("songIdList的值为："+songIdList);

        //使用set进行去重
        Set<Long> songIdSet = new HashSet<>(songIdList);
//        System.out.println("去重后的songIdSet为："+songIdSet);

        // 然后根据song_id列表遍历查询song表中的歌曲和歌手
        List<SongDTO> listVo = new ArrayList<SongDTO>();
        for (Long songId : songIdSet) {
            SongDTO songDTO = new SongDTO();
            Song song = songMapper.selectSongBySongId(songId);
            songDTO.setSongId(song.getSongId());
            songDTO.setSongName(song.getSongName());
            songDTO.setSinger(song.getSinger());
            songDTO.setFileUrl(song.getFileUrl());
            //在计算播放的次数，插入对应歌曲的播放的次数字段的数据
            songDTO.setPlayCount(historyMapper.getPlayCount(songId));
            listVo.add(songDTO);
        }
//        System.out.println("listVo的值为："+listVo);
        return listVo;
    }

    @Override
    public List<SongVo> getSongListBySingerId(Long singerId) {
        //获取歌手
        Singer singer = singerMapper.selectSingerBySingerId(singerId);
        List<Song>list =songMapper.getSongListBySingerId(singer.getSingerName());
//        System.out.println("list的值"+list);
        List<SongVo> listVo = new ArrayList<SongVo>();
        for (Song song1 : list) {
            SongVo songVo = new SongVo();
            songVo.setSongId(song1.getSongId());
            songVo.setSongName(song1.getSongName());
            songVo.setSinger(song1.getSinger());
            songVo.setReleaseDate(song1.getReleaseDate());
            songVo.setImgUrl(song1.getImgUrl());
            songVo.setFileUrl(song1.getFileUrl());
            songVo.setLyric(song1.getLyric());
            listVo.add(songVo);
        }
//        System.out.println("返回列表为："+listVo);
        return listVo;

    }

    @Override
    public List<SongVo> searchSong(SearchLogDTO searchLogDTO) {
        if (searchLogDTO.getKeyword()!=null){
//            System.out.println("keyword的值为："+keyword);
            Song song = new Song();
            song.setSongName(searchLogDTO.getKeyword());
            List<Song>list1 =songMapper.selectSongList(song);
//            System.out.println("第一步"+list1);
            if (list1.size()==0) {//通过歌曲名没有搜索到歌曲，就按照歌手搜索
                Song song1=new Song();
                song1.setSinger(searchLogDTO.getKeyword());
                System.out.println("song的值为："+song1);
                List<Song>list =songMapper.selectSongList(song1);
                System.out.println("搜索到的list"+list);
                System.out.println("list的值"+list);
                List<SongVo> listVo = new ArrayList<SongVo>();
                for (Song song2 : list) {
                    SongVo songVo = new SongVo();
                    songVo.setSongId(song2.getSongId());
                    songVo.setSongName(song2.getSongName());
                    songVo.setSinger(song2.getSinger());
                    songVo.setReleaseDate(song2.getReleaseDate());
                    songVo.setImgUrl(song2.getImgUrl());
                    songVo.setFileUrl(song2.getFileUrl());
                    songVo.setLyric(song2.getLyric());
                    listVo.add(songVo);
                }
                return listVo;
            }else{
                //搜索到歌曲，就返回歌曲,且添加到指定的搜索结果日志表中
                List<SongVo> listVo = new ArrayList<SongVo>();
                for (Song song1 : list1) {
                    SongVo songVo = new SongVo();
                    songVo.setSongId(song1.getSongId());
                    songVo.setSongName(song1.getSongName());
                    songVo.setSinger(song1.getSinger());
                    songVo.setReleaseDate(song1.getReleaseDate());
                    songVo.setImgUrl(song1.getImgUrl());
                    songVo.setFileUrl(song1.getFileUrl());
                    songVo.setLyric(song1.getLyric());

                    //添加到搜索日志表中
                    Searchlog searchlog = new Searchlog();
                    searchlog.setSongId(song1.getSongId());
                    searchlog.setUserId(searchLogDTO.getUserId());
                    searchlogMapper.insertSearchlog(searchlog);
                    listVo.add(songVo);
                }
                return listVo;
            }

        }
        return null;
    }

    @Override
    public List<Singer> searchSinger(String keyword) {
        if (keyword!=null){
            Singer singer = new Singer();
            singer.setSingerName(keyword);
            return singerMapper.selectSingerList(singer);
        }
        return null;
    }

    @Override
    public List<Album> searchAlbum(String keyword) {
        if (keyword!=null){
            Album album = new Album();
            album.setAlbumName(keyword);
            return albumMapper.selectAlbumList(album);
        }
        return null;
    }



    @Override
    public List<Song> getWaitingSongList(int[] songIds) {
        List<Song>songList=new ArrayList<>();
        for (int songId : songIds){
            Song song = songMapper.getSongBySingerId(songId);
            songList.add(song);
        }
        return songList;
    }

    @Override
    public List<String> getMusicType() {
        System.out.println("获取到的音乐类型为雷暴去1111："+songMapper.getMusicType());
        List<String> uniqueList = new ArrayList<>(new LinkedHashSet<>(songMapper.getMusicType()));

        //去重
        System.out.println("去重之后的值为："+uniqueList);
        return songMapper.getMusicType();
    }

    @Override
    public List<Song> addLikeType(LikeType likeType) {
        //添加用户喜欢标签
        songMapper.addLikeType(likeType);
        //将JSON数据转换为List
        String likeType1 = likeType.getLikeType();
        List<String> likeTypesList = JSON.parseArray(likeType1, String.class);
        List<Song> songList1 = new ArrayList<>();
        //获取用户喜欢标签的歌单
        for (String likeType2 : likeTypesList) {
            System.out.println("likeType2的值为："+likeType2);
            List<Song> songList2 = songMapper.getSongListByType(likeType2);
            System.out.println("songList2的值为："+songList2);
            //一个类型的数据插入三首歌曲
            for (int i = 0; i < 3; i++) {
                songList1.add(songList2.get(i));
            }
        }
//        System.out.println("获取的喜好标签的音乐列表为:"+songList1);

        //将数据插入到recommendations表中
            for (Song recommendSong : songList1) {
                Recommendations recommendations = new Recommendations();
                recommendations.setUserId(likeType.getUserId());
                recommendations.setSongId(recommendSong.getSongId());
                recommendations.setRecommendTime(new Date());
                recommendations.setType("OnLine");
                recommendationsMapper.insertRecommendations(recommendations);
            }
        return songList1;
    }

    /**
     * 获取用户离线推荐表中的歌曲
     * @param userId
     * @return
     */
    @Override
    public List<Song> getOffLineRecommendSongs(int userId) {
        List<Song> songList = new ArrayList<>();
        List<Long> recommendSongIds = recommendationsMapper.getSongIdByUserId(userId);
        for (Long songId : recommendSongIds) {
            Song song = songMapper.selectSongBySongId(songId);
            songList.add(song);
        }
        return songList;
    }


    /**
     *  离线推荐（在定时任务中运行）
     * @param userId
     * @throws InterruptedException
     */
    public List<Song> OffLineRecommendModel(int userId) {
        // 内存数据存储（生产环境应使用Redis）
        List<UserProfile> userProfiles = new ArrayList<>();//所有用户画像

        System.out.println("开始推荐");

        //获取用户表里的所有用户
        List<Long> userIdsList = userMapper.getAllUserIds();

        System.out.println("所有userId列表为："+userIdsList);

        //更新到所有用户的userProfiles内存中
        for (Long userId1 : userIdsList) {
                UserProfile userProfile = new UserProfile();
                userProfile.setUserId(String.valueOf(userId1));
                ////////////////////////获取所有用户的redis中的歌曲行为记录///////////////////////////
                    // 获取userIdsList中指定用户的播放历史最后 10 条记录
                    List<Long> listeningHistorySongIds = redisTemplate.opsForList().range("user:" + userId1 + ":listeningHistory", -10, -1);

                    if (listeningHistorySongIds != null) {
//                        System.out.println("播放历史");
                        for (Long songId : listeningHistorySongIds) {
                            userProfile.updatePlayHistory(String.valueOf(songId));
                        }
                    }

                    //获取userIdsList中指定用户收藏最后 10 条记录
                    List<Long> favoriteSongIds = redisTemplate.opsForList().range("user:" + userId1 + ":favorite", -10, -1);
                    //将String的转化为
                    if (favoriteSongIds != null) {
//                        System.out.println("收藏");
                        for (Long songId : favoriteSongIds) {
                            userProfile.updateFavorites(String.valueOf(songId));
                        }
                    }

                    //获取userIdsList中指定用户的搜索最后 10 条记录
                    List<String> searchKeyWords= redisTemplate.opsForList().range("user:" + userId1 + ":search", -10, -1);

                    //将String的转化为
                    if (searchKeyWords != null) {
//                        System.out.println("搜索");
                        for (String keyWord : searchKeyWords) {
                            userProfile.updateSearchKeywords(String.valueOf(keyWord));
                        }
                    }
                userProfiles.add(userProfile);
        }
        OffLineRecommendationEngine engine = new OffLineRecommendationEngine(songMapper);

        // 初始化歌曲元数据
        engine.initializeSongs(songMapper.selectSongList(null));

        List<Song> recommendSongs=  engine.startProcessing(userProfiles,userId);//开始推荐

        System.out.println("end。。。。。");
        return recommendSongs;
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 实时推荐
     * @param userActionEvents
     * @throws InterruptedException
     */
    @Override
    public List<Song> getOnLineRecommendSongs(BlockingQueue<UserActionEvent> userActionEvents) throws InterruptedException {

        System.out.println("实时接收的行为数据："+userActionEvents);
        //处理冷启动问题（判断userActionEvents中的songId、action、keyword是否为null）
        if (userActionEvents.peek().getSongId()==null&&userActionEvents.peek().getAction()==null&&userActionEvents.peek().getKeyword()==null){
            List<Song> songList = new ArrayList<>();
            System.out.println("根据用户选择的喜好标签后推荐的歌曲111："+Integer.parseInt(userActionEvents.peek().getUserId()));
            //获取根据用户选择的喜好标签后推荐的歌曲
            List<Long> songIdList = recommendationsMapper.getSongIdByUserId2(Integer.parseInt(userActionEvents.peek().getUserId()));
            //获取列表
            for (Long songId : songIdList) {
                Song song = songMapper.selectSongBySongId(songId);
                songList.add(song);
            }
            System.out.println("根据用户选择的喜好标签后推荐的歌曲："+songList);
            return songList;
        }

        // 内存数据存储（生产环境应使用Redis）
        List<UserProfile> userProfiles = new ArrayList<>();//所有用户画像
//        List<SongProfile> songMetadata = new ArrayList<>();//歌曲元数据

        System.out.println("开始推荐"+userActionEvents);

        /**
         * redis中的userIdsList部分
         */
        Set keys = redisTemplate.keys("user:*");
//        System.out.println("keys的值为："+keys);
        List<Long> userIdsList = new ArrayList<>();
        //将userId添加到userIdsList中
        for (Object key : keys) {
            String keyStr = (String) key;  //user:100:favorite
            if (keyStr.contains("user:")) {
                String userId1 = keyStr.substring(5,8);
                userIdsList.add(Long.parseLong(userId1));
            }
        }
        //将userIdsList中重复的值去掉
        for (int i = 0; i < userIdsList.size(); i++) {
            for (int j = i + 1; j < userIdsList.size(); j++) {
                if (userIdsList.get(i).equals(userIdsList.get(j))) {
                    userIdsList.remove(j);
                    j--;
                }
            }
        }System.out.println("redis中存有的所有userId列表为："+userIdsList);
        //更新到所有用户的userProfiles内存中
        for (Long userId1 : userIdsList) {
            UserProfile userProfile = new UserProfile();
            userProfile.setUserId(String.valueOf(userId1));

            ////////////////////////获取它的redis中的歌曲行为记录///////////////////////////
            // 获取userIdsList中指定用户的播放历史最后 10 条记录
            List<Long> listeningHistorySongIds = redisTemplate.opsForList().range("user:" + userId1 + ":listeningHistory", -10, -1);
            if (listeningHistorySongIds != null) {
                for (Long songId : listeningHistorySongIds) {
                    userProfile.updatePlayHistory(String.valueOf(songId));
                }
            }

            //获取userIdsList中指定用户收藏最后 10 条记录
            List<Long> favoriteSongIds = redisTemplate.opsForList().range("user:" + userId1 + ":favorite", -10, -1);
            //将String的转化为
            if (favoriteSongIds != null) {
                for (Long songId : favoriteSongIds) {
                    userProfile.updateFavorites(String.valueOf(songId));
                }
            }

            //获取userIdsList中指定用户的搜索最后 10 条记录
            List<String> searchKeyWords= redisTemplate.opsForList().range("user:" + userId1 + ":search", -10, -1);
            //将String的转化为
            if (searchKeyWords != null) {
//                        System.out.println("搜索");
                for (String keyWord : searchKeyWords) {
                    userProfile.updateSearchKeywords(String.valueOf(keyWord));
                }
            }
            userProfiles.add(userProfile);
        }

        //删除掉本用户的个人档案，在重新加入
        if (userActionEvents.peek()!=null){ //如果不为空，则删除掉本用户的个人档案
            userProfiles.removeIf(userProfile -> userProfile.getUserId().equals(String.valueOf(userActionEvents.peek().getUserId())));
        }
        System.out.println("本用户的行为队列的值为1："+userActionEvents);

        //额外添加本用户的个人档案
        UserProfile userProfile = new UserProfile();
        userProfile.setUserId(String.valueOf(userActionEvents.peek().getUserId()));

        //由于队列独有的数据结构特点，所以需要将用户个人行为userActionEvents队列中的数据复制出来一个副本用来抽取行为数据，再进行操作
        BlockingQueue<UserActionEvent> userActionEvents2 = new LinkedBlockingQueue<>(userActionEvents);

        while (!userActionEvents2.isEmpty()) {
            UserActionEvent event = userActionEvents2.take();//注意这里是一个阻塞队列，所以获取一个，删除一个,直到为空
            if (event.getAction()==ActionType.PLAY){
                userProfile.updatePlayHistory(String.valueOf(event.getSongId()));
            }else if (event.getAction()==ActionType.FAVORITE){
                userProfile.updateFavorites(String.valueOf(event.getSongId()));
            }else if (event.getAction()==ActionType.SEARCH){
                userProfile.updateSearchKeywords(String.valueOf(event.getKeyword()));
            }
        }
        System.out.println("本用户的行为队列的值为2："+userActionEvents2);//已被取出，队列为空
        System.out.println("原本的用户行为队列："+userActionEvents);
        userProfiles.add(userProfile);

        // 初始化推荐引擎
        OnLineRecommendationEngine engine = new OnLineRecommendationEngine(songMapper);

        // 初始化歌曲元数据
        engine.initializeSongs(songMapper.selectSongList(null));

        // 开始处理事件流
        List<Song> recommendSongs= new ArrayList<>();
        if (userActionEvents.peek() != null) {
            recommendSongs = engine.startProcessing(userProfiles,Integer.parseInt(userActionEvents.peek().getUserId()));
        }

        System.out.println("end。。。。。");

        //删除自己的推荐歌曲
        if (userActionEvents.peek() != null) {
            recommendationsMapper.deleteRecommendationsByUserId(userActionEvents.peek().getUserId());
        }
        //将数据插入到recommendations表中
        if (recommendSongs != null) {
            for (Song recommendSong : recommendSongs) {
                Recommendations recommendations = new Recommendations();
                if (userActionEvents.peek() != null) {
                    recommendations.setUserId(Long.parseLong(userActionEvents.peek().getUserId()));
                }
                recommendations.setSongId(recommendSong.getSongId());
                recommendations.setRecommendTime(new Date());
                recommendations.setType("OnLine");
                recommendationsMapper.insertRecommendations(recommendations);
            }
        }
        return recommendSongs;
    }

    @Override
    public List<Song> getLikeTypeMusic(int userId) {
        List<Long> songIdByUserId2 = recommendationsMapper.getSongIdByUserId2(userId);
        List<Song> songList = new ArrayList<>();
        for (Long songId : songIdByUserId2){
            songList.add(songMapper.selectSongBySongId(songId));
        }
//        System.out.println("getLikeTypeMusic张:"+songList);
        return songList;
    }

    @Override
    public List<SongDTO> getNewSongs() {
        List<Song> songList = songMapper.getNewSongs();
        List<SongDTO> songVoList = new ArrayList<>();
        //遍历检查收听历史里有没有这些音乐id
        for (Song song : songList) {
            Long playCount = historyMapper.getPlayCount(song.getSongId());
            if (playCount != null) {
                SongDTO songDTO = new SongDTO();
                songDTO.setSongId(song.getSongId());
                songDTO.setSongName(song.getSongName());
                songDTO.setFileUrl(song.getFileUrl());
                songDTO.setSinger(song.getSinger());
                songDTO.setType(song.getType());
                songDTO.setPlayCount(playCount);
                songVoList.add(songDTO);
            }
        }
        return songVoList;
    }

    @Override
    public List<TypeSongListCount> getEachTypeSongListCount() {
        //获取所有的歌曲类型
        List<SongCategory> songTypes = songCategoryMapper.getSongTypeList();
        List<TypeSongListCount> typeSongListCounts = new ArrayList<>();
        for (SongCategory songType : songTypes) {
            TypeSongListCount typeSongListCount = new TypeSongListCount();
            typeSongListCount.setSongType(songType.getCategoryName());
            int count=songMapper.getTypeSongCount(songType.getCategoryName());
            typeSongListCount.setCount(count);
            typeSongListCounts.add(typeSongListCount);
        }
        //放序列化
        return typeSongListCounts;
    }

}
